package logic

import (
	"context"
	"errors"
	"manuscript-service/manurpc/internal/svc"
	"manuscript-service/manurpc/manurpc"
	"manuscript-service/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuAddLogic {
	return &ManuAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *ManuAddLogic) ManuAdd(in *manurpc.ManuAddRequest) (*manurpc.ManuAddResponse, error) {
	// todo: add your logic here and delete this line
	var findtitle model.Manu
	tx := model.DB.Begin()
	if err := findtitle.FindManuByTitle(tx, in.Title); err == nil {
		tx = tx.Rollback()
		return nil, errors.New("已存在")
	}
	class := model.Class{
		ClassName: in.ClassName,
	}
	if err := class.FindClassByName(tx, in.ClassName); err != nil {
		tx = tx.Rollback()
		return nil, errors.New("类别创建失败")
	}
	data := model.Manu{
		Title: in.Title,
		Looks: int(in.Looks),
		Cid:   int(class.ID),
	}
	if err := data.ManuAdd(tx); err != nil {
		tx = tx.Rollback()
		return nil, errors.New("新增失败")
	}
	tx = tx.Commit()
	return &manurpc.ManuAddResponse{
		ManuId: int64(data.ID),
	}, nil
}
